package com.example.mqtt.base;

import com.example.mqtt.device.properties.DeviceMqttProperties;
import com.example.mqtt.device.receiver.DeviceMqttReceiver;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.List;
import java.util.UUID;

@Configuration
@EnableConfigurationProperties(value = {DeviceMqttProperties.class})
public class MqttConfig {

    @Bean(value = "deviceMqttClient")
    public MqttClient deviceMqttClient(List<DeviceMqttReceiver> receivers, DeviceMqttProperties properties)
            throws MqttException {
        // MQTT连接选项
        MqttConnectOptions mqttConnectOptions = new MqttConnectOptions();
        // 用户名
        mqttConnectOptions.setUserName(properties.getUsername());
        // 密码
        mqttConnectOptions.setPassword(properties.getPassword().toCharArray());
        // 超时时间(s)
        mqttConnectOptions.setConnectionTimeout(properties.getConnectionTimeout());
        // 心跳时间(s)
        mqttConnectOptions.setKeepAliveInterval(properties.getKeepAliveInterval());
        // 自动重连
        mqttConnectOptions.setAutomaticReconnect(true);
        // 设置自动重连最大延时(ms)
        mqttConnectOptions.setMaxReconnectDelay(properties.getMaxReconnectDelay());
        // 设置最大飞行窗口
        mqttConnectOptions.setMaxInflight(properties.getMaxInflight());


        // 生成客户端ID
        String clientId = properties.getClientIdPrefix().concat(":").concat(UUID.randomUUID().toString());
        // 构造MQTT客户端
        MqttClient mqttClient = new MqttClient(properties.getBrokerUrl(), clientId, new MemoryPersistence());
        // 读取超时时间(s)
        mqttClient.setTimeToWait(properties.getTimeToWait());
        // 设置回调
        mqttClient.setCallback(new MqttCallback(mqttClient, receivers));

        // 连接
        mqttClient.connect(mqttConnectOptions);

        return mqttClient;
    }
}
